package top.xzxsrq.common.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 列表工具
 *
 * @program: MyUtils
 * @create: 2022-04-15 19:45
 **/
public abstract class DistinctKeyUtilZX {
    /**
     * 列子-单个字段： List<Integer> list1 = Arrays.asList(1, 1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 6, 9, 10);
     *         List<Integer> list3 = list1
     *                 .stream()
     *                 .filter(DistinctKeyUtilZX.distinctByKey(n -> n))
     *                 .collect(Collectors.toList());
     *         System.out.println("list3 = " + list3);
     *         list3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
     * 列子-多个字段：     class test {
     *             final int field1;
     *             final int field2;
     *
     *             public test(int field1, int field2) {
     *                 this.field1 = field1;
     *                 this.field2 = field2;
     *             }
     *
     *             @Override
     *             public String toString() {
     *                 return "test{" +
     *                         "field1=" + field1 +
     *                         ", field2=" + field2 +
     *                         '}';
     *             }
     *         }
     *
     *         List<test> list1 = Arrays.asList(
     *                 new test(0,1),
     *                 new test(0,2),
     *                 new test(0,3),
     *                 new test(0,1),
     *                 new test(0,2),
     *                 new test(0,3)
     *         );
     *         List<test> list3 = list1
     *                 .stream()
     *                 .filter(DistinctKeyUtilZX.distinctByKey(n -> n.field1 + n.field2))
     *                 .collect(Collectors.toList());
     *         System.out.println("list3 = " + list3);
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
